package com.dji.compose_learning.ui.view

import android.util.Log
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

@Composable
fun BackHandler(backDispatcher: OnBackPressedDispatcher, onBack: () -> Unit) {
    val currentOnBack by rememberUpdatedState(onBack)
    val backCallback = object :OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
//            onBack()
            currentOnBack()
        }
    }

    DisposableEffect(backDispatcher) {
        backDispatcher.addCallback(backCallback)
        onDispose { //这里重组合的时候会执行
            backCallback.remove()
            Log.i("buobao","dispose running")
        }
    }
}

@Composable
fun DisposableEffectView(backDispatcher: OnBackPressedDispatcher) {
    var checkedState by rememberSaveable {
        mutableStateOf(false)
    }
    val context = LocalContext.current
    if (checkedState) {
        BackHandler(backDispatcher = backDispatcher) {
            Toast.makeText(context,"当前不能返回",Toast.LENGTH_SHORT).show()
        }
    }

    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
        Row(modifier = Modifier.wrapContentHeight(),
            verticalAlignment = Alignment.CenterVertically) {
            Switch(checked = checkedState, onCheckedChange = {
                checkedState = it
            })
            Spacer(modifier = Modifier.width(10.dp))
            Text(text = if (checkedState) "禁止返回" else "可以返回")
        }
    }
}